package com.jasiri.project.ui.user.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.jasiri.project.R
import com.jasiri.project.adapter.FeedbackImageAdapter
import com.jasiri.project.adapter.KefuContactAdapter
import com.jasiri.project.databinding.ActivityFeedbackBinding
import com.jasiri.project.databinding.ItemQuestionTypeBinding
import com.jasiri.lib.baseadapter.JasiriOnItemChildClickListener
import com.jasiri.project.pro.ProActivity
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.http.IHttpCallback
import com.jasiri.project.utils.imagecovert.ImageConvert
import com.jasiri.project.utils.log.HHLog
import org.json.JSONObject
import java.io.File

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/28 11:50
 * @Annotation：意见反馈
 */
class FeedbackActivity: ProActivity() {
    lateinit var binding: ActivityFeedbackBinding

    //联系方式列表
    private var mContactAdapter: KefuContactAdapter? = null
    //反馈类型列表
    private var typeList: ArrayList<JSONObject>? = null
    //图片列表
    private var mImgAdapter: FeedbackImageAdapter? = null

    //图片压缩后存储的临时文件
    var destinationDirectory: File? = null
    //图片选择
    private lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    override fun getRootView(): View {
        binding = ActivityFeedbackBinding.inflate(layoutInflater)
        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        setTitleBarVisibility(View.VISIBLE)
        setTextTitle(getString(R.string.personal_feedback))
        setTextTitleGravity(Gravity.CENTER)
        setRightBtnVisibility(View.GONE)

        initRecyclerView()
        initImageRecyclerView()
        binding.tvLength.text = "0/1000"

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                HHLog.e("uri.path>>>>>>>>>>>>>>${uri.path}")
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    HHLog.e(">>>>>>>>>>>>>localPath: $localPath")
                    if (localPath != null){
                        mImgAdapter?.let {
                            //最多只能选三张
                            if (it.itemCount == 3){
                                it.removeItem(0)
                            }
                            val imgObj = JSONObject()
                            imgObj.put("isDefault",false)
                            imgObj.put("imgPath",localPath)
                            it.addLastItem(imgObj)
                        }
                        uploadImageAction(localPath)
                    }
                }

            } else {
                HHLog.e("No media selected")
            }
        }
    }

    override fun initListener() {
        //联系客服
//        rootViewBinding.ivFun.setOnClickListener {
//            onIntent(UserFeedbackAct::class.java)
//            TrackEventUtils.logEvent(TrackEventType.CLICK.CLICK_CUSTOMER,"UserFeedback Page")
//        }
        //输入框监听
        binding.editRemark.addTextChangedListener(IEditChangeListener)
        binding.editRemark.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus && binding.editRemark.text.toString().isNotEmpty()){
                addEvent(EventType.FORM.FORM_USER_FEEDBACK_DESCRIBE,binding.editRemark.text.toString())
            }
        }
        //提交
        binding.btnSubmit.setOnClickListener {
            //问题类型
            if (getSelectTypeItem() == null){
                showToast(getString(R.string.feedback_please_select_question_type))
                return@setOnClickListener
            }
            val remark = binding.editRemark.text.toString()
            if (remark.isEmpty()){
                showToast(getString(R.string.feedback_briefly_hint))
                return@setOnClickListener
            }
            showLoading()
            val params = JSONObject().addCommonParams().apply {
                put("path", AppUrls.PATH.FEEDBACK_SUBMIT)
                put("opinion",remark)//反馈内容
            }
            getSelectTypeItem()?.let {
                params.put("type",it.optString("value"))//反馈类型
            }
            onSubmitFeedbackAction(params)
            addEvent(EventType.CLICK.CLICK_USER_FEEDBACK_SUBMIT,"")
        }
    }

    override fun initData() {
        loadContactListAction()
        loadQuestionTypeListAction()

        val imgObj = JSONObject()
        imgObj.put("isDefault",true)
        mImgAdapter?.addFirstItem(imgObj)
    }

    /**
     * 初始化联系方式列表
     */
    private fun initRecyclerView() {
        binding.rvContact.setHasFixedSize(false)
        binding.rvContact.isNestedScrollingEnabled = false
        binding.rvContact.isFocusableInTouchMode = false //不需要焦点
        binding.rvContact.layoutManager = LinearLayoutManager(this)
        mContactAdapter = KefuContactAdapter(binding.rvContact)
        binding.rvContact.adapter = mContactAdapter
        binding.rvContact.itemAnimator = DefaultItemAnimator()
        mContactAdapter?.setOnItemChildClickListener(JasiriOnItemChildClickListener { parent, childView, position ->
            mContactAdapter?.let {
                val item = it.getItem(position)
                when (childView.id) {
                    R.id.btnDial -> {//拨号
                        onCallAction(item)
                    }
                }
            }
        })
    }

    /**
     * 初始化图片列表
     */
    private fun initImageRecyclerView() {
        binding.rvImgs.setHasFixedSize(false)
        binding.rvImgs.isNestedScrollingEnabled = false
        binding.rvImgs.isFocusableInTouchMode = false //不需要焦点
        binding.rvImgs.layoutManager = GridLayoutManager(this,3)
        mImgAdapter = FeedbackImageAdapter(binding.rvImgs)
        binding.rvImgs.adapter = mImgAdapter
        binding.rvImgs.itemAnimator = DefaultItemAnimator()
        mImgAdapter?.setOnItemChildClickListener(JasiriOnItemChildClickListener { parent, childView, position ->
            mImgAdapter?.let {
                val item = it.getItem(position)
                when (childView.id) {
                    R.id.imgDelete -> {//删除
                        if (!item.optBoolean("isDefault")) {
                            it.removeItem(position)

                            //是否需要添加默认图片
                            var isAddDefault = true
                            for (i in 0..<it.itemCount) {
                                if (it.getItem(i).optBoolean("isDefault")) {
                                    isAddDefault = false
                                    break
                                }
                            }
                            if (isAddDefault) {
                                val imgObj = JSONObject()
                                imgObj.put("isDefault", true)
                                it.addFirstItem(imgObj)
                            }
                        }
                    }

                    R.id.imgView -> {//选择图片
                        if (item.optBoolean("isDefault")) {
                            hasRequestPermissions()
                        }
                    }
                }
            }
        })
    }

    private val IEditChangeListener = object: TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
        @SuppressLint("SetTextI18n")
        override fun afterTextChanged(s: Editable?) {
            val textLength = s?.length
            binding.tvLength.text = "$textLength/1000"
        }
    }

    /**
     * 设置问题类型列表
     */
    private fun showQuestionTypeView(){
        binding.flexboxLayout.removeAllViews()
        typeList?.let { list ->
            for (i in 0..< list.size) {
                val item = list[i]
                val itemBinding = ItemQuestionTypeBinding.inflate(layoutInflater)
                itemBinding.textTitle.text = item.optString("title")
                if (item.optBoolean("isSelect")){
                    itemBinding.textTitle.setTextColor(ContextCompat.getColor(this,R.color.white))
                    itemBinding.textTitle.setBackgroundResource(R.drawable.btn_selector_radius)
                } else {
                    itemBinding.textTitle.setTextColor(ContextCompat.getColor(this,R.color.FF828282))
                    itemBinding.textTitle.setBackgroundResource(R.drawable.radius_frame_f5f3ef_12)
                }
                binding.flexboxLayout.addView(itemBinding.root)
                itemBinding.textTitle.setOnClickListener {
                    if (item.optBoolean("isSelect")){
//                    item.put("isSelect",false)
//                    setQuestionTypeList()
                        return@setOnClickListener
                    }
                    for (index in 0..< list.size){
                        val obj = list[index]
                        if (index == i){
                            obj.put("isSelect",true)
                            addEvent(EventType.CLICK.CLICK_USER_FEEDBACK_QUESTION_TYPE,obj.optString("title"))
                        } else {
                            obj.put("isSelect",false)
                        }
                    }
                    showQuestionTypeView()
                }
            }
        }
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject){
        val type = item.optString("type")
        addEvent(EventType.CLICK.CLICK_USER_FEEDBACK_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        startActivity(callIntent)
    }

    /**
     * 申请权限
     */
    private fun hasRequestPermissions(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 获取选择的问题类型
     */
    private fun getSelectTypeItem(): JSONObject?{
        var selectItem: JSONObject? = null
        typeList?.let {
            for (i in 0..< it.size){
                val obj = it[i]
                if (obj.optBoolean("isSelect")){
                    selectItem = obj
                    break
                }
            }
        }
        return selectItem
    }

    /**
     * 设置联系方式列表
     */
    private fun setContactList(contactList: ArrayList<JSONObject>) {
        mContactAdapter?.data = contactList
    }

    /**
     * 设置意见反馈问题类型列表
     */
    private fun setQuestionTypeList(dataList: ArrayList<JSONObject>) {
        if (typeList == null){
            typeList = arrayListOf()
        }
        typeList?.clear()
        typeList?.addAll(dataList)
        showQuestionTypeView()
    }

    /**
     * 获取联系方式列表
     */
    private fun loadContactListAction(){
        val data = JSONObject(Configs.getSPString(Configs.SPKEY.JASIRI_COMMON))
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                contactList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                contactList.add(obj)
            }
            setContactList(contactList)
        }
    }

    /**
     * 获取问题类型列表
     */
    private fun loadQuestionTypeListAction(){
        val dataList = arrayListOf(
            "Product Suggestion,SUGGEST",
            "App bugs,BUG",
            "Payment issues,PAYMENT",
            "Others,OTHER")
        val typeList = arrayListOf<JSONObject>()
        for (i in 0..<dataList.size){
            val items = dataList[i].split(",")
            val obj = JSONObject()
            obj.put("title", items[0])
            obj.put("value", items[1])
            obj.put("isSelect",false)
            typeList.add(obj)
        }
        setQuestionTypeList(typeList)
    }

    /**
     * 上传图片
     */
    private fun uploadImageAction(imgPath: String){
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.FILE)
        uploadFileAction(httpUrl,File(imgPath),object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                data.optJSONObject("obj")?.let {
                    val imgUrl = it.optString("url")
                    addEvent(EventType.CLICK.CLICK_USER_FEEDBACK_UPLOAD_IMAGE,imgUrl)
                }
                destinationDirectory?.let {
                    if (it.isFile){
                        it.delete()
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 提交意见反馈
     */
    private fun onSubmitFeedbackAction(params: JSONObject){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val code = data.optInt("code")
                val msg = data.optString("msg")
                showToast(msg)
                Handler(Looper.getMainLooper()).postDelayed({
                    finish()
                },500)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_USER_FEEDBACK_START,"")
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_USER_FEEDBACK_END,"")
    }
}